package com.wstuo.itsm;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.wstuo.common.util.StringUtils;


/**
 * 会话过滤方法
 * @author WSTUO
 *
 */
public class SessionFilter implements Filter{
	private static final Logger LOGGER = Logger.getLogger(SessionFilter.class);
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException  {
		
		try{
			HttpSession session = ((HttpServletRequest) request).getSession();
			HttpServletResponse res=(HttpServletResponse) response ;
			HttpServletRequest req = (HttpServletRequest) request;
			
			
			String url = req.getRequestURI();
			String ctx_path = req.getContextPath();
			String userName = (String) session.getAttribute("loginUserName");
//			if(!StringUtils.hasText(userName)){
//				userName = (String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//			}
//			String userName1 = (String) session.getAttribute("SPRING_SECURITY_LAST_USERNAME");
			if(url.substring(ctx_path.length()).indexOf("access")!=-1){   //允许访问
				chain.doFilter(request, response);
				return;
			}
			if(!StringUtils.hasText(userName) && !filterPage(url)) { //如果session有用户名证明还是登录中的, 
				res.sendError(606);
				return;
			}else{
				chain.doFilter(request, response);
				return;
			}
	   }catch(Exception ex){
		   LOGGER.error(ex);
	   }
	}	
	private String[] strs = new String[]{
			"login.jsp",
			"reg.jsp",
			"trial.jsp",
			"requestVisit.jsp",
			"userReturnVisit!replyUserReturnVisit.action",
			"visit!findVisit.action",
			"j_spring_security_check",
			"user!findDisable.action",
			"user!findUserByPassword.action",
			"uploadFile!uploadAttr.action",
			"module!uploadHarFile.action",
			"configData!importConfigData.action",
			"user!userLogin.action",
			"auto-login.jsp",
			"user!autoLogin.action",
			"user!LDAPAuthAndUpdate.action",
			"user!resetPassword.action",
			"email!toEmail.action",
			"email!findPasswordToEmail.action",
			"user!userExist.action",
			"RetakePasswordByEmail.jsp",
			"welcome.jsp",
			"ci!updateOneCi.action",
			"ci!updateCi.action",
			"overdue.jsp",
			"license!uploadLicense.action",
			"licenseKey!validateKey.action",
			"activation.jsp",
			"license!checkLicenseCode.action",
			"request!createRequest.action",
			"email!sendEmail.action",
			"tableUpdate!addTableUpdate.action",
			"tableUpdate!serviceDirectoryList.action",
			"user!userActivation.action",
			"copyrightmd5!JudgeMD5.action",
			"copyrightmd5!JudgeMD5save.action",
			"Escala!Upgrade.action",
			"timeZone!loadClientTimeZone.action",
			"user!passwordUpgrade.action",
			"event!getCategoryTree.action",
			"organization!findCompany.action",
			"knowledgeInfo!showKnowledge.action",
			"affiche!loginFindAllAffiche.action",
			"affiche!findAfficheDTOById.action",
			"affiche!find.action",
			"ciInfoAction!findByciIdClent.action",
			"attachment!download.action",
			"historyRecord!saveHistoryRecord.action",
			"user!findUserByRandomNum.action",
			"historyRecord!findAllHistoryRecordByClient.action",
			"noticeRule!findByFileNameReturnDTO.action",
			"jbpm!ifExistTaskId.action",
			"flowProperty!findFlowActivityById.action",
			"jbpm!findFlowActivity.action",
			"jbpm!ifExistTaskId.action",
			"jbpm!processDetail.action",
			"request!processHandle.action",
			"problem!processHandle.action",
			"change!processHandle.action",
			"release!processHandle.action",
			"request!showRequestInfo.action",
			"knowledgeInfo!findAllKnowledges.action",
			"immanage!delete.action",
			"dataDictionaryItems!findByCode.action",
			"dataDictionaryItems!findByCodeJsonp.action",
			"client!version.action",
			"copyrightmd5!copyright.action",
			"clientUser!addUser.action",
			"clientCim!saveCItemClient.action",
			"schema!createSchema.action",
			"schema!configDataLoader.action",
			"schema!updateSchema.action",
			"schema!createDatabase.action",
			"schema!tenantDataInit.action",
			"schema!configureFileInit.action",
			"user!updateOnLineRegisterStatus.action",
			"configData!preparingConfigure.action",
			"organization!getImageUrlforimageStream.action",
			"request!findProcessAssignDTO.action",
			"problem!findProcessAssignDTO.action",
			"change!findProcessAssignDTO.action",
			"release!findProcessAssignDTO.action",
			"problem!problemToPrint.action",
			"change!changeToPrint.action",
			"knowledgeInfo!saveCommentKnowledge.action",
			"sms!sendsms_reg.action",
			"user!regByPhone.action",
			"user!findUserByLoginName.action",
			"release!findById.action"
	};
	public boolean filterPage(String url){
		boolean result=false;
		
		for(int i=0;i<strs.length;i++){
			if(url.endsWith(strs[i])){
				result = true;
			}
		}
		return result;
	}
		
	public void init(FilterConfig fConfig) throws ServletException {
	}
	
	
	
}
